﻿using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SysCommon.WinServices
{
    /// <summary>
    /// 服务调用控制
    /// </summary>
    public class WinServiceController
    { 
        /// <summary>
        /// 服务开始启用
        /// </summary>
        /// <typeparam name="T">服务调用的类型</typeparam>
        /// <param name="ServiceName">服务的名称</param>
        /// <param name="args">应用程序启动传入的参数</param>
        public static void Start<T>(string ServiceName, object argsObj)
            where T : ServiceBase, IServiceController, new()
        {
            string[] args = (string[])argsObj;
            string key0 = AppDomain.CurrentDomain.FriendlyName;
            if (args.Length > 0)
            {
                string str = args[0].ToLower();
                try
                {
                    if (str == "-install" || str == "-i")
                    {
                        #region 安装本服务
                        if (null == ServiceIsExisted(ServiceName))
                        {//如果没有安装，则安装
                            string key = AppDomain.CurrentDomain.BaseDirectory + key0;
                            ManagedInstallerClass.InstallHelper(new string[] { key });
                            ServiceController c = new ServiceController(key0.Substring(0, key0.Length - 4));
                            c.Start();
                        }
                        else
                        {
                            SysCommon.Log.Log.Write("服务已经安装！无需再安装！");
                        }
                        #endregion
                    }
                    else if (str == "-uninstall" || str == "-u")
                    {
                        #region 卸载本服务
                        ServiceController sc = ServiceIsExisted(ServiceName);
                        if (null != sc)
                        {//如果已经安装，则卸载本服务
                            if (sc.Status != ServiceControllerStatus.Stopped)
                            {
                                sc.Stop();//停止服务
                                sc.WaitForStatus(ServiceControllerStatus.Stopped);//等待服务完全停止；真方便的函数~
                            }
                            string key = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName;
                            ManagedInstallerClass.InstallHelper(new string[] { "/u", key });
                        }
                        else
                        {
                            SysCommon.Log.Log.Write("服务未安装！不能卸载不存在的服务！");
                        }
                        #endregion
                    }
                    else if (str == "-start" || str == "-s")
                    {
                        #region 将本服务当做一个应用程序直接运行
                        SysCommon.Log.Log.Write("消息服务启动开始");
                        T msm = null;
                        try
                        {
                            msm = new T();
                            msm.Start();
                        }
                        catch (Exception msg)
                        {
                            if (null != msm)
                            {
                                msm.Stop();
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception msg)
                {
                    SysCommon.Log.Log.Write(msg.Message + msg.StackTrace);
                    SysCommon.Log.Log.Write("消息服务异常结束");
                }
            }
            else
            {
                #region //启动本服务
                try
                {
                    ServiceBase.Run(new T());
                }
                catch (Exception msg)
                {
                    SysCommon.Log.Log.Write(msg.Message + msg.StackTrace);
                    SysCommon.Log.Log.Write("消息服务异常结束");
                }
                #endregion
            }

        }

        /// <summary>   
        /// 检查指定的服务是否存在。   
        /// </summary>   
        /// <param name="serviceName">要查找的服务名字</param>   
        /// <returns>如果存在则返回真</returns>   
        private static ServiceController ServiceIsExisted(string svcName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == svcName)
                {
                    return s;
                }
            }
            return null;
        }
    }
}
